
import os
import json
import random
import cmdUtil
import serialUtil
from queue import Queue
import time
import cv2
import math

isTouch = False
# IMGSIZE = (1080,2340) #小米10
# IMGSIZE = (1080,1920)    #小米IMax
IMGSIZE = (768,1024)  #小米

CMDQUEUE = Queue()

os.getcwd()

def onImgSizeChange(s):
    global IMGSIZE
    IMGSIZE = s
    cmdUtil.initCmdUtil(CMDQUEUE,IMGSIZE)




tPecent = 0.01
pPrcent = 0.02

bCmds = []
cmds = []
fname =  's.txt'
def saveScrpit():
    global cmds,bCmds
    outs = ''
    t0 = bCmds[0][1]
    for i,v in enumerate(bCmds):
        c = v[0]
        ti = v[1]
        dt = ti-t0
        t0 = ti
        bCmds[i] = [c,dt]
        outs += c + ':' + str(dt) + '\n'
    f  = open(fname,'w')
    f.write(outs[:-1])
    f.close()


def randomTime():
    global cmds
    cmds = []
    for i,v in enumerate(bCmds):
        if v[0][0] == '{':
            v[0][0] = '['
            v[0][-1] = ']'
            dc = json.loads(v[0])
            dx1 = random.randint(int(dc[0]-(dc[0]*pPrcent)/2),int(dc[0]+(dc[0]*pPrcent)/2))
            dy1 = random.randint(int(dc[1]-(dc[1]*pPrcent)/3),int(dc[1]+(dc[1]*pPrcent)/3))
            dx2 = random.randint(int(dc[2]-(dc[2]*pPrcent)/2),int(dc[2]+(dc[2]*pPrcent)/2))
            dy2 = random.randint(int(dc[3]-(dc[3]*pPrcent)/3),int(dc[3]+(dc[3]*pPrcent)/3))
            dsp = random.randint(int(dc[4]-(dc[4]*pPrcent)/2),int(dc[4]+(dc[4]*pPrcent)/2))
            dt = random.randint(int(v[1]-(v[1]*tPecent)/2),int(v[1]+(v[1]*tPecent)/2))
            print(dc,dt)
            cmds.append(['{%d,%d,%d,%d,%d}'%(dx1,dy1,dx2,dy2,dsp),dt])
        else:
            dc = json.loads(v[0])
            dx = random.randint(int(dc[0]-(dc[0]*pPrcent)/2),int(dc[0]+(dc[0]*pPrcent)/2))
            dy = random.randint(int(dc[1]-(dc[1]*pPrcent)/3),int(dc[1]+(dc[1]*pPrcent)/3))
            dt = random.randint(int(v[1]-(v[1]*tPecent)/2),int(v[1]+(v[1]*tPecent)/2))
            print(dc,dt)
            cmds.append(['[%d,%d,%d]'%(dx,dy,dc[2]),dt])

def runScrpt(fpth = None):
    global cmds,bCmds,fname
    if not bCmds or fpth:
        bCmds = []
        f = None
        if fpth:
            f = open(fpth,'r')
        dat = f.read()
        f.close()
        lines = dat.split('\n')
        for i,v in enumerate(lines):
            tmpc = v.split(':')
            c = tmpc[0]
            dt = int(tmpc[1])
            bCmds.append([c,dt])
    print(bCmds)
    randomTime()
    print(cmds)
    for i,v in enumerate(cmds):
        time.sleep(v[1]/1000.0)
        cmdUtil.sendCmd(v[0])

def touchMove(p0,p1,speed):
    tcmd = cmdUtil.touchMoveTo(p0,p1,speed)
    bCmds.append(tcmd)


def mPressFunc(x,y,flags):
    global isTouch,bCmds
    isTouch = True
    print('press',x,y,flags)
    tcmd = cmdUtil.press(x,y)
    if flags == 9:
        bCmds.append(tcmd)

durgs = []

def mReleaseFunc(x,y,flags):
    global isTouch,bCmds,durgs
    isTouch = False
    print('release',x,y,flags)
    tcmd = cmdUtil.release(x,y)
    if flags == 8:
        if durgs:
            tmpp = json.loads(durgs[0][0])
            p0 = [tmpp[0],tmpp[1]]
            tmpp2 = json.loads(tcmd[0])
            p1 = [tmpp2[0],tmpp2[1]]
            dt = tcmd[1] - durgs[0][1]
            l = math.sqrt((p0[0]-p1[0])**2+(p0[1]-p1[1])**2)
            speed = int(1000*l/dt)
            touchMove(p0,p1,speed)
            durgs.clear()
        else:
            bCmds.append(tcmd)

def mMoveFunc(x,y,flags):
    global durgs
    print('move',x,y,flags)
    if isTouch:
        tcmd = cmdUtil.press(x,y)
        if flags == 9:
            durgs.append(tcmd)
    else:
        cmdUtil.release(x,y)

def onMouse_Event(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDOWN:
        mPressFunc(x,y,flags)
    #左键抬起
    elif event == cv2.EVENT_LBUTTONUP:
        mReleaseFunc(x,y,flags)
    elif event == cv2.EVENT_MOUSEMOVE:
        mMoveFunc(x,y,flags)

def delayS(ts,n):
    for i in range(ts):
        print('run:%d times,delay:%d'%(n,ts - i))
        time.sleep(1)

def baoxiang():
    runScrpt('bx.txt') #宝箱
def hongbaoyu():
    runScrpt('hby.txt')#红包雨
def kanju():
    runScrpt('kj.txt') #看剧
def fanpiao():
    runScrpt('jg.txt') #饭票


def onKey_Event(key):
    global bCmds,cmds
    print(key)
    if key == 32 or key == 13:  #空格:32,#回车:13
        pass
    if key == 27:    #ESC按键,退出程序
        exit(0)      
    if key == 48: #数字0
        print('0')
    elif key == 49: #数字1
        print('1')
        saveScrpit()
    elif key == 50: #数字2
        print('2')
        while True:
            for i in range(4):
                runScrpt('bx.txt')
                dt = random.randint(1,6)
                delayS(180+dt,i)
            runScrpt('hby.txt')
            dt = random.randint(10,60)
            delayS(dt,-1)
    elif key == 51: #数字3
        print('3')
        bCmds = []
        cmds = []

def touchInit():
    cmdUtil.release(0,0)
    time.sleep(0.1)
    cmdUtil.release(540,960)
    time.sleep(0.1)
    cmdUtil.release(1080,1920)
    time.sleep(0.1)
    cmdUtil.release(540,960)
    time.sleep(0.1)
    cmdUtil.release(0,0)

def main():
    net_thread = serialUtil.serialThread(CMDQUEUE)
    net_thread.setDaemon(True)
    net_thread.start()
    time.sleep(3)
    winname = 'fengmm521.taobao.com'
    cv2.namedWindow(winname)
    cmdUtil.initCmdUtil(CMDQUEUE,IMGSIZE)
    time.sleep(0.12)
    img = cv2.imread('m.jpg')
    cmdUtil.initCmdUtil(CMDQUEUE,(img.shape[1],img.shape[0]))
    cv2.setMouseCallback(winname, onMouse_Event)
    while True:
        cv2.imshow(winname, img)
        key = cv2.waitKey(0)
        if key > 0:
            onKey_Event(key)

if __name__ == '__main__':  
    main()
